package de.medizin.uni.halle.irm;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;

public class ReceiveMailFragment extends SherlockFragment {
	private ArrayAdapter<String> listAdapter; 
	SQLiteDatabase database;
	Cursor c;
	View rm;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rm = (LinearLayout)inflater.inflate(R.layout.receive, container, false);
    	((Button) rm.findViewById(R.id.receive_button)).setOnClickListener(new View.OnClickListener(){
			public void onClick(View arg0) {
				if(!new MailSystem(getSherlockActivity()).getMails(getSherlockActivity()))
		       		Toast.makeText(getSherlockActivity(), "Mails konnten nicht abgerufen werden", Toast.LENGTH_LONG).show();
				else 
					updateEmailList(rm);
			}
    	});
		updateEmailList(rm);
        return rm;        
	}
	
    private void setonclick(ListView lv) {
	    lv.setOnItemClickListener(new OnItemClickListener()
	    {
	    	public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
	    	{	
	    		final String idString = (String) ((TextView) v.findViewById(R.id.ID_CELL)).getText();
	    		database = getSherlockActivity().openOrCreateDatabase("born", Context.MODE_PRIVATE, null);	
	    		c = database.rawQuery("Select history.sid, firstname, lastname, content, date from history LEFT JOIN patients ON history.sid = patients.sid where history._id ="+
	    				idString+";" , null);
	    		c.moveToFirst();
	    		
	    		Context mContext = getSherlockActivity();
            	final Dialog dialog = new Dialog(mContext);

            	dialog.setContentView(R.layout.mail_dialog);
            	dialog.setTitle("EMail von "+c.getString(c.getColumnIndex("firstname"))+" "+c.getString(c.getColumnIndex("lastname"))+
            			" (SID:" + c.getString(c.getColumnIndex("sid")) +") vom " + c.getString(c.getColumnIndex("date")));	
            	dialog.setCanceledOnTouchOutside(true);

            	TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
            	text.setText(c.getString(c.getColumnIndex("content")));
            	dialog.show();
            	
            	LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.layout_root);
               
                final Cursor c2 = database.rawQuery("SELECT * FROM questions WHERE state = 'active' ORDER BY position", null);
                c2.moveToFirst();
                Cursor c3 = null;
                
                LinearLayout line = new LinearLayout(dialog.getContext());
                line.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                line.setOrientation(1);
                layout.addView(line, 3);
                for (int i = 0; i < c2.getCount(); i++) {
                    LinearLayout l = new LinearLayout(dialog.getContext());
                    l.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                    l.setOrientation(0);
                    TextView question = new TextView(dialog.getContext());
                    question.setText(c2.getString(c2.getColumnIndex("question")));
                    question.setId(c2.getInt(c2.getColumnIndex("_id")));
                    Spinner answer_spinner = new Spinner(dialog.getContext());
                    c3 = database.rawQuery("SELECT * FROM answers WHERE question_id = '" + c2.getString(c2.getColumnIndex("_id")) +"';", null);
                    String[] from = new String[]{"answer"};
                    int[] to = new int[]{android.R.id.text1};
                    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getSherlockActivity(), android.R.layout.simple_spinner_item, c3, from, to, 0);
                    adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
                    answer_spinner.setAdapter(adapter);         
                    answer_spinner.setId(Integer.parseInt(c2.getString(c2.getColumnIndex("_id"))+"00"));                
                    line.addView(l);
                    l.addView(question);
                    l.addView(answer_spinner);
                    c2.moveToNext();
                }
         	
                Button save = (Button) dialog.findViewById(R.id.save);
                save.setOnClickListener(new OnClickListener() {
                	public void onClick(View v) {
                		c2.moveToFirst();  
                		String ev ="";
                		for(int i = 0;i<c2.getCount();i++){
                			String qid = c2.getString(c2.getColumnIndex("_id"));
                			Spinner sp = (Spinner) dialog.findViewById(Integer.parseInt(qid+"00"));
                			Cursor cc = (Cursor) sp.getSelectedItem();                			                			
                			ev = ev + qid + ":" + cc.getString(cc.getColumnIndex("_id"))+";";  
                			c2.moveToNext();
                		}
                		Toast.makeText(getSherlockActivity(), ev, Toast.LENGTH_SHORT).show();
                		ContentValues evaluation = new ContentValues();
                		evaluation.put("evaluation", ev);
                		database.update("history",evaluation,"_id ="+idString, null);
                		dialog.dismiss();
                		updateEmailList(rm);
                	}
                });
            	
                Button cancel = (Button) dialog.findViewById(R.id.cancel);
                cancel.setOnClickListener(new OnClickListener() {
                	public void onClick(View v) {
                		dialog.dismiss();
                    }
                });
	        }
	     });
	} 
    
	private void updateEmailList(final View v) {
		database = getSherlockActivity().openOrCreateDatabase("born", Context.MODE_PRIVATE, null);	
		ListView lv  = (ListView) v.findViewById(R.id.rm_listview);				
    	int[] to = new int[] { R.id.ID_CELL, R.id.SID_CELL, R.id.LASTNAME_CELL, R.id.FIRSTNAME_CELL, R.id.DATE_CELL };
        String[] fields = new String[] {"_id","sid","lastname", "firstname", "date",};
    	c = database.rawQuery("Select history._id, patients.sid,firstname,lastname, historytype, type, date from history LEFT JOIN patients ON history.sid = patients.sid " +
    			"WHERE historytype='email received' AND evaluation is null order by date;" , null);
    	if(c.getCount()>0){
	    	CursorAdapter data = new SimpleCursorAdapter(getSherlockActivity(), R.layout.receive_mail_row, c, fields, to, 0 );
	    	lv.setAdapter(data);  
	    	((ListView) v.findViewById(R.id.rm_listview)).setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS);
	    	setonclick(lv);
    	}
    	else {
    		String[] mails = new String[] {"Keine EMails im Posteingang"}; 
            listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_overview, mails);  
            lv.setAdapter( listAdapter ); 
            ((ListView) v.findViewById(R.id.rm_listview)).setOverScrollMode(View.OVER_SCROLL_NEVER);
    	}	
    	database.close();
	}
}
